#pragma once

#include <iostream>
#include <stdint.h>
#include <poll.h>
#include <vector>
#include "log.hpp"
#include "Socket.hpp"

static const uint16_t defaultport = 8888;
// fd_set最多可存放1024个文件描述符
static const int fd_num = 64;
int defaultfd = -1;
int non_event = 0;

class PollServer
{
public:
    PollServer(uint16_t port = defaultport)
        : _port(port), fd_num_max(fd_num)
    {
        _event_fds = new struct pollfd[fd_num_max];
        // 初始化数组
        for (int i = 0; i < fd_num_max; i++)
        {
            _event_fds[i].fd = defaultfd;
            _event_fds[i].events = non_event;
            _event_fds[i].revents = non_event;
        }
    }
    ~PollServer()
    {
        _listensock.Close();
    }
    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();

        return true;
    }
    // 扩容
    void reserve()
    {
        struct pollfd *tmp = new struct pollfd[fd_num_max * 2];
        for (int i = 0; i < fd_num_max; i++)
        {
            if (i < fd_num_max)
            {
                tmp[i].fd = _event_fds[i].fd;
                tmp[i].events = _event_fds[i].events;
                tmp[i].revents = _event_fds[i].revents;
                continue;
            }
            _event_fds[i].fd = defaultfd;
            _event_fds[i].events = non_event;
            _event_fds[i].revents = non_event;
        }
        _event_fds = tmp;
        delete[] tmp;
        fd_num_max *= 2;
    }
    void Accepter()
    {
        // 连接事件已就绪
        std::string clientip;
        uint16_t clientport = 0;
        int sock = _listensock.Accept(clientip, clientport);
        if (sock < 0)
            return;
        lg(Info, "accept success, %s: %d, sock fd: %d", clientip.c_str(), clientport, sock);

        // 将已就绪的套接字放入用户维护的数组
        int pos = 1;
        for (; pos < fd_num_max; pos++)
        {
            // 要么遍历完1024个元素退出，要么遇到defaultfd退出
            if (_event_fds[pos].fd != defaultfd)
                continue;
            else
                break;
        }
        // 遍历了数组，没有发现有-1，说明数组已满，则扩容
        if (pos == fd_num_max)
        {
            lg(Warning, "server is full, reserve %d now!", fd_num_max);

            // 扩容
            reserve();
        }
        // 发现有-1，则将该套接字存入数组内
        _event_fds[pos].fd = sock;
        _event_fds[pos].events = POLLIN;
        _event_fds[pos].revents = non_event;
        PrintFd();
    }
    void Recver(int fd, int pos)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "get a message: " << buffer << std::endl;
        }
        else if (n == 0)
        {
            lg(Info, "client quit, me too, close fd is: %d", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd; // 这里是为了将套接字从select中移除
        }
        else
        {
            lg(Warning, "recv error: fd is: %d", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd; // 这里是为了将套接字从select中移除
        }
    }
    // 输出数组内维护的套接字
    void PrintFd()
    {
        std::cout << "online fd list: ";
        for (int i = 0; i < fd_num_max; i++)
        {
            if (_event_fds[i].fd == defaultfd)
                continue;
            std::cout << _event_fds[i].fd << " ";
        }
        std::cout << std::endl;
    }
    // 文件描述符就绪 && 该套接字是listen监听的套接字
    void Dispatcher()
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            int fd = _event_fds[i].fd;
            if (fd == defaultfd)
                continue;

            // 事件已就绪
            if (_event_fds[i].revents & POLLIN)
            {
                // fd是listen监听的套接字，连接事件就绪
                if (fd == _listensock.Fd())
                {
                    std::cout << "get a new link!!!" << std::endl;
                    Accepter(); // 连接管理器
                }
                // 不是listen套接字，读事件就绪
                else
                {
                    Recver(fd, i);
                }
            }
        }
    }
    void Start()
    {
        _event_fds[0].fd = _listensock.Fd();
        _event_fds[0].events = POLLIN;
        int timeout = -1;
        for (;;)
        {
            int n = poll(_event_fds, fd_num_max, timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out, timeout..." << std::endl;
                break;
            case -1:
                std::cerr << "select error" << std::endl;
                break;
            default:
                // 有事件就绪了
                Dispatcher();
                break;
            }
        }
    }

private:
    Sock _listensock;
    uint16_t _port;
    struct pollfd *_event_fds;          // 用户维护的数组
    int fd_num_max;                     // 用户维护的数组大小
};